package com.y3k.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.y3k.utils.ConfigurationUtil;

public class Mail {

	public static boolean sendMessage(String subject, String body, String[] mailToList) {

		MailConfiguration mailConfiguration = ConfigurationUtil.MAIL;

		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", mailConfiguration.getProtocol());
		props.setProperty("mail.host", mailConfiguration.getHost());
		props.setProperty("mail.smtp.auth", mailConfiguration.getAuthentication().toString());
		props.setProperty("mail.smtp.port", mailConfiguration.getPort().toString());

		Session mailSession = Session.getDefaultInstance(props, new SMTPAuthentication());
		mailSession.setDebug(true);
		Transport transport;
		try {
			transport = mailSession.getTransport();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
			return false;
		}

		MimeMessage message = new MimeMessage(mailSession);
		try {
			message.setSubject(subject);
			message.setFrom(new InternetAddress(mailConfiguration.getMail()));
			message.setContent(body, "text/html");
			transport.connect(mailConfiguration.getMail(), mailConfiguration.getPassword());

			if (mailToList != null) {
				for (String mail : mailToList) {
					message.addRecipient(Message.RecipientType.TO, new InternetAddress(mail.trim()));
				}
			}
			transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
			transport.close();
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}